package config

import (
	"net/http"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"

	"cgs-server/helper"
	"cgs-server/server"
)

func init() {
	//server.Handle(http.MethodPost, "/api/Config/Save", Save, server.Administrator)
	server.Post("/api/Config/Save", Save, "保存配置信息", server.ManageBackend)
	server.Post("/api/Config/Sys/Update", saveConfig, "保存系统配置信息", server.ManageBackend)
}

// Save save system config.
func Save(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	defaultRegisterRole, err := primitive.ObjectIDFromHex(r.FormValue("DefaultRegisterRole"))

	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	var doc bson.M
	find, _ := db.FindOne(server.ConfigCollectionName, bson.M{}, &doc)

	if !find {
		doc = bson.M{
			"ID":                  primitive.NewObjectID(),
			"Initialized":         false,
			"DefaultRegisterRole": defaultRegisterRole,
		}
		db.InsertOne(server.ConfigCollectionName, doc)
	} else {
		update := bson.M{
			"$set": bson.M{
				"DefaultRegisterRole": defaultRegisterRole,
			},
		}
		db.UpdateOne(server.ConfigCollectionName, bson.M{}, update)
	}

	helper.WriteJSON(w, server.Result{
		Code: 200,
		Msg:  "Save Successfully.",
		Data: bson.M{
			"DefaultRegisterRole": defaultRegisterRole,
		},
	})
}

func saveConfig(w http.ResponseWriter, r *http.Request) {

	conf := &SystemConfig{}

	if err := helper.ReadRequestBody(conf, w, r); err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	var res SystemConfig
	find, _ := db.FindOne(server.ConfigCollectionName, bson.M{"type": "system"}, &res)

	if find {

		update := bson.M{
			"$set": bson.M{
				"logo":                   conf.Logo,
				"ico":                    conf.Ico,
				"name":                   conf.Name,
				"domainRegistrationInfo": conf.DomainRegistrationInfo,
				"bgImg":                  conf.BgImg,
				"theme":                  conf.Theme,
			},
		}
		_, err = db.UpdateOne(server.ConfigCollectionName, bson.M{"type": "system"}, update)

	} else {

		res.Type = "system"
		_, err = db.InsertOne(server.ConfigCollectionName, conf)
	}

	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	helper.WriteJSON(w, server.OK("Update successfully!"))

}
